<?php
header('Access-Control-Allow-Origin: *');

// 解析body及子栏
$body = json_decode($_POST['body'], true);
$select = $body['select'];
$update = $body['update'];
$insert = $body['insert'];
$delete = $body['insert'];

// 声明sqls, params
$sqls = [];
$params = [];

// 处理select
foreach ($select as $key=>$val) {
    
    // 取变量
    $table = $val['table'];
    $column = $val['column'] ?? '*';
    $order = $val['order'] ?? '';
    $limit = $val['limit'] ?? '';
    $group = $val['group'] ?? '';
    $where = $val['where'] ?? '';

    // 如果table不存在，则报错

    // 解析order, group, limit
    if ($order != '') $order = " order by ${order}";
    if ($group != '') $group = " group by ${group}";
    if ($limit != '') $limit = " limit ${limit}";

    // 解析where
    $wheres = [];
    foreach ($where as $wk=>$wv) {
        
        // 判断wv类型（where子句中的操作类型）
        $value = getWhereValue($wv);

        // 设置使用了session的值
        $value = getSessionValue($value);

        // 设置使用了RPC的值
        $value = getRPCValue($value);

        
    }

    print_r($wheres);
  

    // 连接sqls和params
    // $sqls[] = "select ${column} from ${table} where ${where} ${group} ${order} ${limit}";
    // $params[] = [

    // ];

}

/**
 * 判断where类型
 *
 * @param string $src
 * @return void
 */
function getWhereValue($src) {

    // in语句不需要计算，直接正常返回
    if (LString::has($src, 'in(')) return $src;          
    
    // 计算like
    if (LString::has($src, 'like(')) {
        $keyword = LString::middle($src, 'like(', ')');
        return "like %${keyword}%";
    }

    // 计算between
    if (LString::has($src, 'between(')) {
        $values = LString::middle($src, 'between(', ')');
        $tmp = LString::split($values, ',');
        return 'between ' . $tmp[0] . ' and ' . $tmp[1];
    }

    // 计算gte
    if (LString::has($src, 'gte(')) {
        $value = LString::middle($src, 'gte(', ')');
        return ">=${value}";
    }

    // 计算gt
    if (LString::has($src, 'gt(')) {
        $value = LString::middle($src, 'gt(', ')');
        return ">${value}";
    }

    // 计算lte
    if (LString::has($src, 'lte(')) {
        $value = LString::middle($src, 'lte(', ')');
        return ">${value}";
    }

    // 计算lt
    if (LString::has($src, 'lt(')) {
        $value = LString::middle($src, 'lt(', ')');
        return ">${value}";
    }

    // 无特殊计算，等号
    return "=${src}";
}

/**
 * Undocumented function
 *
 * @param [type] $src
 * @return void
 */
function getWhereSession($src) {

}

/**
 * Undocumented function
 *
 * @param [type] $src
 * @return void
 */
function getWhereRPC($src) {

    // 获取10位时间戳
    if (LString::has($src, '$.time.get10(')) return Time::get10();

    // 获取13位时间戳
    if (LString::has($src, '$.time.get13(')) return Time::get13();

    // password加密字符串
    if (LString::has($src, '$.password(')) {
        $value = LString::middle($src, '$.password(', ')');
        return md5($value);
    }
}
